<?php
namespace app\controller;

use think\Request;
use think\facade\Db;

class Xhsbazaar extends Common
{

	/**
	 * 查询数据
	 *
	 * @return
	 */
	public function read(Request $request) {
		if($this->hasPermission($request->sessInfo, 'xhsbazaar:read')) {
			return ['code'=> 403, 'msg'=> '你没有权限执行此操作!'];;
		}

		$where = [];
		$limit = $request->param('limit/d', 20);
		$sort = $request->param('sort', 'id', 'trim');
		$order = $request->param('order', 'desc', 'trim');

		$name = $request->param('name', '', 'trim');
		if($name) {
			array_push( $where, ['name', 'like',  "%{$name}%" ] );
		}

		$query = Db::name('cfg_xhs_bazaar')->where($where)->order($sort, $order)->paginate($limit);

		return ['code'=> 0, 'msg'=> '', 'count'=> $query->total(), 'data'=> $query->items()];
	}

	/**
	 * 更新数据
	 *
	 * @return
	 */
	public function update(Request $request) {
		if($this->hasPermission($request->sessInfo, 'xhsbazaar:update')) {
			return ['code'=> 403, 'msg'=> '你没有权限执行此操作!'];;
		}

		$param = $request->param();
		if( isset($param['state']) ) {
			$status = $request->param('status', '', 'trim');
			Db::name('cfg_xhs_bazaar')
					->where('id', $param['state'])
					->update([ 'status' => $status]);
			return ['code'=>0, 'msg'=>'操作成功'];
		}

		$id = $request->param('id', '', 'trim');
		$name = $request->param('name', '', 'trim');
		$sort = $request->param('sort', '', 'trim');
		$status = $request->param('status', '', 'trim');
		Db::name('cfg_xhs_bazaar')->where('id', $id)->update([ 'name' => $name, 'sort' => $sort, 'status' => $status]);
		return ['code'=>0, 'msg'=>'操作成功'];
	}

	/**
	 * 创建数据
	 *
	 * @return
	 */
	public function create(Request $request) {
		if($this->hasPermission($request->sessInfo, 'xhsbazaar:save')) {
			return ['code'=> 403, 'msg'=> '你没有权限执行此操作!'];;
		}
		$name = $request->param('name', '', 'trim');
		$sort = $request->param('sort', '', 'trim');
		$status = $request->param('status', '', 'trim');
		$query = Db::table('cfg_xhs_bazaar')->where('name', $name)->value('name');
		if(!empty($query)) {
			return ['code'=>403, 'msg'=>'操作失败, 市场已存在!'];
		}
		Db::name('cfg_xhs_bazaar')->insert([ 'name' => $name, 'sort' => $sort, 'status' => $status, 'datatime' => date('Y-m-d H:i:s')]);
		return ['code'=>0, 'msg'=>'操作成功'];
	}

	/**
	 * 删除数据
	 *
	 * @return
	 */
	public function delete(Request $request) {
		if($this->hasPermission($request->sessInfo, 'xhsbazaar:delete')) {
			return ['code'=> 403, 'msg'=> '你没有权限执行此操作!'];;
		}
		$param = $request->param();
		if( !isset($param['id']) ) {
			return ['code'=> 403, 'msg'=> '操作失败!'];
		}
		$index = 0;
		$explode = explode(',', $param['id']);
		foreach( $explode as $value ) {
			$query = Db::table('cfg_xhs_keywords')->where('bazaarId', $value)->value('id');
			if(empty($query)) {
				$index++;
				Db::table('cfg_xhs_bazaar')->where('id', $value)->delete();
			}
		}
		return ['code'=> 0, 'msg'=> '成功删除'.$index.'个行业!'];
	}

}
